/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tbenglish_client.form;

import bllInterface.Account;
import bllfactory.SBLLFactory;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import model.ClientFriendListModel;
import model.ClientModel;
import model.chat.ChatMessageModel;

/**
 *
 * @author Mrkupi
 */
public class menu extends javax.swing.JFrame implements ListDataListener
{
    ClientFriendListModel   model;
    DefaultListModel newModel   =   new DefaultListModel();
    ArrayList<String> strModel  =   new ArrayList();    
    
    public menu(  ) {
        initComponents();
        setLocation( 800, 50 );
        
        this.model  =   new ClientFriendListModel();
        model.addListDataListener(this);
        
        initWindowCustomize();
        
        loadFriendList();
    }
    
    private void initWindowCustomize(){
        setResizable(false);
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
            }
        });
        
        scrollPaneFriendlist = new javax.swing.JScrollPane();
        friendList  =   new javax.swing.JList( model ){
             @Override
             public String getToolTipText(MouseEvent e)
             {
                 int index = locationToIndex(e.getPoint());
                 if (-1 < index) 
                 {
                     return strModel.get( index );
                 } 
                 else 
                 {
                     return null;
                 }
             }
        };
        scrollPaneFriendlist.setViewportView(friendList);
        friendList.setLocation( 180, 110);
        friendList.setVisible( true );
        friendList.setSize(270, 380);
        friendList.setBorder(BorderFactory.createLineBorder(Color.black));
        friendList.addMouseListener( new MouseAdapter(){
            @Override
            public void mousePressed( MouseEvent e )
            {
            }
            
            @Override
            public void mouseClicked( MouseEvent e ){
                if( e.getClickCount() == 2 ){
                    Object selected =   friendList.getSelectedValue();
                    String strRoom  =   (String) selected;
                    Account acc = model.getAcc(strRoom);
                    if( acc != null )
                    {
                        try {
                            createPrivateChat( acc.getUserID(), acc.getUserName() );
                        } catch (RemoteException ex) {
                            Logger.getLogger(roomChat.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        } );
        this.add( friendList );
    }
    
    public void createPrivateChat( String id, String name ){
        ChatMessageModel chatMsgModel = new ChatMessageModel();
        ClientModel.getInstance().getChatMsgModels().put(id, chatMsgModel);
        new privateChat(chatMsgModel, id, name).setVisible(true);
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btChatBox = new javax.swing.JButton();
        btGame = new javax.swing.JButton();
        btSearch = new javax.swing.JButton();
        btMessages = new javax.swing.JButton();
        btRequest = new javax.swing.JButton();
        btInfo = new javax.swing.JButton();
        tfSearch = new javax.swing.JTextField();
        btEnter = new javax.swing.JButton();
        add = new javax.swing.JButton();
        btnSignOut = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel1.setText("MENU");

        btChatBox.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\Community Help.png")); // NOI18N
        btChatBox.setText("CHAT AREA");
        btChatBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btChatBoxActionPerformed(evt);
            }
        });

        btGame.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\AlienAqua Joystick.png")); // NOI18N
        btGame.setText("GAME");
        btGame.setPreferredSize(new java.awt.Dimension(90, 60));

        btSearch.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\AQUA ICONS SYSTEM SHERLOCK.png")); // NOI18N
        btSearch.setText("SEARCH");
        btSearch.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btSearchMouseClicked(evt);
            }
        });

        btMessages.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\CRISTAL MAIL.png")); // NOI18N
        btMessages.setText("MESSAGES");
        btMessages.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btMessagesMouseClicked(evt);
            }
        });

        btRequest.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\add_user.png")); // NOI18N
        btRequest.setText("REQUEST");
        btRequest.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btRequestMouseClicked(evt);
            }
        });

        btInfo.setIcon(new javax.swing.ImageIcon("E:\\Projects\\Java\\tbenglish\\TBEnglish_Client\\src\\tbenglish_client\\form\\Image\\EXCLAMATION1.png")); // NOI18N
        btInfo.setText("INFO");
        btInfo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btInfoMouseClicked(evt);
            }
        });

        tfSearch.setToolTipText("name");
        tfSearch.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                ontfSearch_type(evt);
            }
        });

        btEnter.setText("Search");
        btEnter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEnterActionPerformed(evt);
            }
        });

        add.setText("+");
        add.setToolTipText("add friend");
        add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addActionPerformed(evt);
            }
        });

        btnSignOut.setText("SIGN OUT");
        btnSignOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSignOutActionPerformed(evt);
            }
        });
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSignOut, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(190, 190, 190)
                            .addComponent(jLabel1))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(21, 21, 21)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(btChatBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btGame, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btSearch, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btMessages, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btRequest, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btInfo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btEnter)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addComponent(add))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(jLabel1)
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btChatBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btGame, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btMessages, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btRequest, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(tfSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(btEnter)
                        .addComponent(add)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                .addComponent(btnSignOut)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btChatBoxActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try 
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } 
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(userInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                if( !RoomContainer.Container.containsKey("World"))
                {
                    worldChat wc = new worldChat();
                    RoomContainer.Container.put( "World", wc);
                    wc.setVisible( true );
                }
            }
        });
    }
    
    private void btSearchMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btSearchMouseClicked
        
    }//GEN-LAST:event_btSearchMouseClicked

    private void btMessagesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btMessagesMouseClicked
        try 
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } 
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(userInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new worldChat().setVisible( true );
            }
        });
    }//GEN-LAST:event_btMessagesMouseClicked

    private void btRequestMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btRequestMouseClicked
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } 
        catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(userInfo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new friendRequest().setVisible( true );
            }
        });
    }//GEN-LAST:event_btRequestMouseClicked

    private void btInfoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btInfoMouseClicked
        new userInfo().setVisible( true );
    }//GEN-LAST:event_btInfoMouseClicked

    private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
        try {
            String selected =   (String)friendList.getSelectedValue();
            SBLLFactory.getInstance().getRelation().sendRequestFriend( ClientModel.getInstance().getAccount().getUserID(), 
                       (String)friendList.getSelectedValue() );
        } catch (RemoteException ex) 
        {
            Logger.getLogger(menu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_addActionPerformed

    private void btEnterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEnterActionPerformed
        search(true, '1');
    }//GEN-LAST:event_btEnterActionPerformed

    private void ontfSearch_type(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ontfSearch_type
    
        search(false, evt.getKeyChar());
    }//GEN-LAST:event_ontfSearch_type

    private void btnSignOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSignOutActionPerformed
        
        for(String key : RoomContainer.Container.keySet()){
            if( RoomContainer.Container.get(key) != null ){
                RoomContainer.Container.get(key).dispose();
            }
        }
        
        System.exit(0);
    }//GEN-LAST:event_btnSignOutActionPerformed

    private boolean search(boolean isButtonPressed, char key)
    {
        this.model.clear();
        this.newModel.clear();
        this.friendList.setModel(model);
        
        if( !isButtonPressed || makeSureNotEmptyTextField() )
        {
            try 
            {
                // put code query friend
                model.search(tfSearch.getText() + (key != '\b' ? String.valueOf(key) : ""));
            } 
            catch (RemoteException ex) 
            {
                Logger.getLogger(menu.class.getName()).log(Level.SEVERE, null, ex);
            }
            return true;
        }
        return false;
    }
    
    private void sendSearchRequest( String name )
    {
        try {
            // send to BLL
            List<Account> accs  =   SBLLFactory.getInstance().getQuerry().getUsers(name);
            
            
            for( int i = 0; i < accs.size(); ++i )
            {
                this.model.addAccount( accs.get( i )  );
            }
            
        } catch (RemoteException ex) {
        }
    }
   
    private boolean makeSureNotEmptyTextField()
    {
        if( "".equals( tfSearch.getText() ))
        {
            JOptionPane.showMessageDialog( this, "Empty" );
            return false;
        }
        
        return true;
    }
    
    private void loadFriendList()
    {
        try 
        {
            ArrayList<Account> accs    =   SBLLFactory.getInstance().getQuerry().getUsers("AllAccount");
            
            for( int i = 0; i < accs.size(); ++i )
            {
                this.model.addAccount( accs.get( i ) );
            }
        } 
        catch (RemoteException ex) {
            Logger.getLogger(menu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton add;
    private javax.swing.JButton btChatBox;
    private javax.swing.JButton btEnter;
    private javax.swing.JButton btGame;
    private javax.swing.JButton btInfo;
    private javax.swing.JButton btMessages;
    private javax.swing.JButton btRequest;
    private javax.swing.JButton btSearch;
    private javax.swing.JButton btnSignOut;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JTextField tfSearch;
    // End of variables declaration//GEN-END:variables
    private javax.swing.JList friendList;
    private javax.swing.JScrollPane scrollPaneFriendlist;
    
    @Override
    public void intervalAdded(ListDataEvent e) {
        model = (ClientFriendListModel) e.getSource();
        for (int i = e.getIndex0(); i < e.getIndex1(); ++i)
        {
            Account cm = (Account) model.getElementAt(i);
            try 
            {
                newModel.addElement(cm.getUserName());
                friendList.setModel( newModel );
                
                strModel.add("Level: " + cm.getLevel() + ", Exp: "+ cm.getExp() );
            } 
            catch (RemoteException ex) {
                Logger.getLogger(menu.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void intervalRemoved(ListDataEvent e) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void contentsChanged(ListDataEvent e) {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}
